use super::output::Link;
use super::shell::{expand_tilde, UploadSSLCertificateCmd};
use super::ACME_HOME;
use std::fs::read_to_string;
use std::path::PathBuf;

pub enum SslAlgorithm {
    RSA,
    ECDSA,
}

pub fn get_domain_file(algorithm: &SslAlgorithm, domain: &str, suffix: &str) -> PathBuf {
    match algorithm {
        SslAlgorithm::RSA => expand_tilde(PathBuf::from(
            format!("{ACME_HOME}/{domain}/{domain}.{suffix}").as_str(),
        ))
        .unwrap(),
        SslAlgorithm::ECDSA => expand_tilde(PathBuf::from(
            format!("{ACME_HOME}/{domain}_ecc/{domain}.{suffix}").as_str(),
        ))
        .unwrap(),
    }
}

pub struct AcmeSslAdapter {
    acme_domain_cert_path: PathBuf,
    acme_domain_key_path: PathBuf,
}

impl AcmeSslAdapter {
    pub fn new(algorithm: SslAlgorithm, domain: &str) -> Self {
        AcmeSslAdapter {
            acme_domain_cert_path: get_domain_file(&algorithm, domain, "cer"),
            acme_domain_key_path: get_domain_file(&algorithm, domain, "key"),
        }
    }

    pub fn validate(&self) -> bool {
        self.acme_domain_cert_path.try_exists().is_ok()
            && self.acme_domain_key_path.try_exists().is_ok()
    }

    pub fn sync_to_tc(&self) -> std::io::Result<&'static str> {
        let cert = read_to_string(self.acme_domain_cert_path.to_str().unwrap())?;
        // println!("cert=>{:?}", cert);
        let key = read_to_string(&self.acme_domain_key_path)?;
        // println!("key=>{:?}", key);
        let cmd = UploadSSLCertificateCmd::new(
            &cert[..],
            &key[..],
            Some(Link::new(
                "上传证书",
                "https://cloud.tencent.com/document/api/400/41665",
            )),
        );
        cmd.exec()
    }
}
